/**
 * Created by liold on 2014/11/21.
 */

var baseUrl = "/m";

/**
 * teachingPlanPool
 * @returns {{contains: Function, get: Function, add: Function}}
 */
function createTeachingPlanPool() {

    var teachingPlanPool = [];

    var pool = {
        contains: function (teachingPlan) {
            for (var i = 0; i < teachingPlanPool.length; i++) {
                var tp = teachingPlanPool[i];
                if (tp.id == teachingPlan.id) {
                    return true;
                }
            }
            return false;
        },

        get: function (teachingPlanId) {

            for (var i = 0; i < teachingPlanPool.length; i++) {
                var tp = teachingPlanPool[i];
                if (tp.id == teachingPlanId) {
                    return tp;
                }
            }
            return null;
        },

        getAt: function (i) {
            return teachingPlanPool[i];
        },

        // 添加到pool
        add: function (teachingPlan) {
            if (!this.contains(teachingPlan)) {
                teachingPlanPool.push(teachingPlan);
            }
        },

        size: function () {
            return teachingPlanPool.length;
        }
    }

    return pool;
}

// 是否有改变，用于自动保存
var hasChanged = false;

var teachingPlanPool = createTeachingPlanPool();
var coursePlanValueList = [];

var curTeachingPlans = [];

var curSelectedTeachingPlan = null;
var curSelectedMergedClassTeachingPlans = [];
var leftTableTop ;
var selector;

$(function () {
    setTaskStep("preAssignment");
    initCurrentTeachingPlanList();
    loadPreSchedule();
    autoSave();
    leftTableTop = $("#left-fixed-div").offset().top;
    selector = $("#left-fixed-div");
    $(window).scroll(function(){
        if (leftTableTop < $(window).scrollTop()){
            selector.addClass("left-fixed").removeClass("left-normal");
        }else {
            selector.removeClass("left-fixed").addClass("left-normal");
        }
    });
});

// 加载所有预排课程
function loadPreSchedule() {
    alertInfo("正在加载数据...", 15 * 1000);
    jQuery.ajax({
        //url: baseUrl + "/teachingplan/list?taskId=" + taskId,
        url: baseUrl + "/teachingplan/listForMultiTeachers?taskId=" + taskId,
        cache: false,
        success: function (ret) {
            if (ret != "") {
                var teachingPlanList = eval(ret);
                processTeachingPlanList(teachingPlanList);
            }
        },
        complete: function () {
            hideAlertInfo();
        }
    });
}

// 处理teachingplan，加入teachingplanpool, 加入courseplanvaluelist
function processTeachingPlanList(teachingPlanList) {
    for (var i = 0; i < teachingPlanList.length; i++) {
        var teachingPlan = teachingPlanList[i];
        teachingPlan.id = createTeachingPlanId(teachingPlan);
        // 已使用的课时数
        teachingPlan.lessonsUsed = 0;
        if (teachingPlanPoolContains(teachingPlan)) {
            continue;
        }

        var preSchdules = teachingPlan.preSchedules;

        if (preSchdules != null && preSchdules != "") {
            var lessonTimes = preSchdules.split(",");
            teachingPlan.lessonsUsed = lessonTimes.length;

            for (var j = 0; j < lessonTimes.length; j++) {
                var lessonTime = lessonTimes[j];

                var addOk = addToCoursePlanValueList(teachingPlan, lessonTime);
                if (addOk) {
                    // 控件里加入
                    appentToLessonTimeCol(teachingPlan, lessonTime);
                }
            }
        }

        // 添加到teachingplanpool
        addToTeachingPlanPool(teachingPlan);
    }
}

//==========
function initCurrentTeachingPlanList() {
    loadCourses(true);
}

function selectGrade() {
    loadCourses();
}

function loadCourses(isAutoSelect) {
    var defaultText = "请选择课程";
    var colSelect = $("#selCourse");
    var gradeId = $("#selGrade").find("option:selected").val();

    if (gradeId == "-1") {
        loadItems(colSelect, null, defaultText)
        return;
    }

    jQuery.ajax({
        url: baseUrl + "/jsondata/courses?taskId=" + taskId + "&gradeId=" + gradeId,
        success: function (ret) {
            if (ret != "") {
                var classes = eval(ret);
                if (isAutoSelect) {
                    loadItems(colSelect, classes, null);
                    selectCourse();
                } else {
                    loadItems(colSelect, classes, defaultText);
                }
            }
        }
    });
}

/**
 * 选中课程下拉列表触发
 */
function selectCourse() {
    // 清除当前禁用的课时
    clearDisabledLessonTimes();
    // 当前点亮的关闭
    setMergedClassCourseColsLight(curSelectedTeachingPlan, false);
    // 清除当前的列表
    clearCurrentTeachingPlans();
    //加载列表
    loadTeachingPlanList();
}

// 选择课程,加载teachingplanlist
function loadTeachingPlanList() {
    var gradeId = $("#selGrade").find("option:selected").val();
    var courseId = $("#selCourse").find("option:selected").val();
    if(courseId == undefined){
        return;
    }

    showTeachingPlanLoading(true);
    jQuery.ajax({
        //url: baseUrl + "/teachingplan/list?taskId=" + taskId + "&gradeId=" + gradeId + "&courseId=" + courseId,
        url: baseUrl + "/teachingplan/listForMultiTeachers?taskId=" + taskId + "&gradeId=" + gradeId + "&courseId=" + courseId,
        cache: false,
        success: function (ret) {
            if (ret != "") {
                var teachingPlanList = eval(ret);
                processTeachingPlanList(teachingPlanList);
                var html = "";
                for (var i = 0; i < teachingPlanList.length; i++) {
                    var teachingPlan = getFromTeachingPlanPool(teachingPlanList[i].id);

                    curTeachingPlans.push(teachingPlan);

                    var colId = "tp" + teachingPlan.id;
                    html += "<tr id='" + colId + "' class='teaching-plan-item' isSelected='false' " +
                    "onclick=\"onSelectTeachingPlanItem('" + teachingPlan.id + "')\" " +
                    "onmouseover='overTeachingPlanItem(this);' " +
                    "onmouseout='outTeachingPlanItem(this);'>";
                    html += "<td>" + teachingPlan.courseName + "</td>";
                    html += "<td>" + teachingPlan.gradeName + "</td>" ;
                    html += "<td>" + teachingPlan.className + "</td>" ;
                    html += "<td>" + teachingPlan.teacherName + "</td>";
                    html += "<td field='lessons'>" + teachingPlan.lessonsUsed + "/" + teachingPlan.lessonsPerWeek + "</td>";
                    html += "</tr>";
                }
                var tbody = $("#tbody_teacher_plan_list");
                tbody.html(html);
            }

            showTeachingPlanLoading(false);
        }
    });
}

/**
 * 清除当前操作的TeachingPlan
 */
function clearCurrentTeachingPlans() {
    var teacherPlanListArea = $("#tbody_teacher_plan_list");
    teacherPlanListArea.html("");

    curTeachingPlans = [];
    curSelectedTeachingPlan = null;
    curSelectedMergedClassTeachingPlans = [];
}


// pool中是否有
function teachingPlanPoolContains(teachingPlan) {
    return teachingPlanPool.contains(teachingPlan);
}

// 从pool中获取
function getFromTeachingPlanPool(teachingPlanId) {
    return teachingPlanPool.get(teachingPlanId);
}

// 添加到pool
function addToTeachingPlanPool(teachingPlan) {
    return teachingPlanPool.add(teachingPlan);
}

// 加载显示
function showTeachingPlanLoading(isShow) {
    $("#teaching_plan_loading").hide();
    if (isShow) {
        $("#teaching_plan_loading").show();
    }
}

function overTeachingPlanItem(obj) {
    $this = $(obj);
    $this.addClass("teaching-plan-hover");
}

function outTeachingPlanItem(obj) {
    $this = $(obj);
    $this.removeClass("teaching-plan-hover");
}

// 选中TeachingPlan列表中的一项
function onSelectTeachingPlanItem(teachingPlanId) {
    var oldSelectedTeachingPlan = curSelectedTeachingPlan;
    var oldMergedClassTeachingPlans = curSelectedMergedClassTeachingPlans;

    curSelectedTeachingPlan = null;

    var clickedTeachingPlan = getFromTeachingPlanPool(teachingPlanId);

    // 原来没选择的或原来不是同一个的，则选中当前的
    if (oldSelectedTeachingPlan == null || oldMergedClassTeachingPlans.indexOf(clickedTeachingPlan) < 0) {
        curSelectedTeachingPlan = clickedTeachingPlan;
    }

    // 合班选中
    curSelectedMergedClassTeachingPlans = getCurrentMergedClassTeachingPlans();

    // 清除当前禁用的课时
    clearDisabledLessonTimes();

    // 去除老的选中
    for (var i = 0; i < oldMergedClassTeachingPlans.length; i++) {
        var tp = oldMergedClassTeachingPlans[i];

        // 原来点亮的关闭 移除原来被选择的状态
        if (tp != null) {
            setCourseColLight(tp, false);
            setTeachingPlanColSelectStatus(tp, false);
        }
    }

    // 当前合班的
    for (var i = 0; i < curSelectedMergedClassTeachingPlans.length; i++) {
        var tp = curSelectedMergedClassTeachingPlans[i];

        setTeachingPlanColSelectStatus(tp, true);
        // 点亮当前选择的
        setCourseColLight(tp, true);
    }

    // 设置不排课位置
    setLessonTimesDisabled("true");
}

function setTeachingPlanColSelectStatus(teachingPlan, isSelected) {
    var teachingPlanCol = getTeachingPlanCol(teachingPlan);
    teachingPlanCol.removeClass("teaching-plan-selected");
    teachingPlanCol.attr("isSelected", "false");

    if (isSelected) {
        teachingPlanCol.addClass("teaching-plan-selected");
        teachingPlanCol.attr("isSelected", "true");
    }
}

// 获取teachingplan控件
function getTeachingPlanCol(teachingPlan) {
    return $("#tp" + teachingPlan.id);
}

/**
 *
 * @param teachingPlan
 * @param isLight
 */
function setMergedClassCourseColsLight(teachingPlan, isLight) {
    if (teachingPlan == null) {
        return;
    }

    var teachingPlanList = getMergedClassTeachingPlans(teachingPlan);
    for (var i = 0; i < teachingPlanList.length; i++) {
        setCourseColLight(teachingPlanList[i], isLight);
    }
}

// 设置课程是否点亮
function setCourseColLight(teachingPlan, isLight) {
    if (teachingPlan == null) {
        return;
    }

    var color = isLight ? "#ff0000" : "";
    $("div[teachingPlanId='" + teachingPlan.id + "']").each(function () {
        $(this).css("color", color);
    });
}

// =========

/**
 * 获取与当前选择teachingPlan合班的teachingPlan集合
 * @returns {Array}
 */
function getCurrentMergedClassTeachingPlans() {
    return getMergedClassTeachingPlans(curSelectedTeachingPlan);
}

/**
 * 获取与指定teachingPlan合班的teachingPlan集合
 * @param teachingPlan
 * @returns {Array}
 */
function getMergedClassTeachingPlans(teachingPlan) {
    var mergedClassTeachingPlans = [];

    if (teachingPlan == null) {
        return mergedClassTeachingPlans;
    }

    // 没有合班
    if (teachingPlan.mergedClassGroupNo == 0) {
        mergedClassTeachingPlans.push(teachingPlan);
        return mergedClassTeachingPlans;
    }

    for (var i = 0; i < teachingPlanPool.size(); i++) {
        var tp = teachingPlanPool.getAt(i);
        // 同一个合班号的，在一起
        if (tp.mergedClassGroupNo == teachingPlan.mergedClassGroupNo) {
            mergedClassTeachingPlans.push(tp);
        }
    }
    return mergedClassTeachingPlans;
}

//=================================

// 划过课时区触发
function overLessonTime(col, colId) {
    var $this = $(col);
    $this.addClass("lesson-time-hover");
    var colCoursePlanItem = $("#" + colId);
    colCoursePlanItem.css("cursor", "default");
    if (curSelectedTeachingPlan) {
//            colCoursePlanItem.css("cursor","pointer");
    }
}

function outLessonTime(col) {
    var $this = $(col);
    $this.removeClass("lesson-time-hover");
}


// 设置
function putCourseTo(lessonTime) {
    if(!isMyTask){
        return;
    }

    // 不排课区，不能安排
    var isDisabled = $("#lessonTime_area_" + lessonTime).attr("isDisabled");
    if (isDisabled == "true") {
        return;
    }

    // 合班
    var teachingPlans = getCurrentMergedClassTeachingPlans();

    // 校验是否可以安排
    if (!checkPutCourses(teachingPlans, lessonTime)) {
        return;
    }
    // 检验是否会产生合班课
    //根据用户选择 如果确认 则继续
    if (hasMergedClassCourse(lessonTime)) {
        //弹出对话框提示
        if (!confirm("此行为会产生合班操作，确定继续么？")) {
            return;
        }
    }
    for (var i = 0; i < teachingPlans.length; i++) {

        var teachingPlan = teachingPlans[i];

        // 已设置课时数+1
        teachingPlan.lessonsUsed++;
        // 加入到当前已排的课程中
        addToCoursePlanValueList(teachingPlan, lessonTime);

        // 加到相关区域
        appentToLessonTimeCol(teachingPlan, lessonTime);
        // 当前的点亮
        setCourseColLight(teachingPlan, true);
        // 改变控件课时数显式
        setTeachingPlanColLessons(teachingPlan);
    }

    hasChanged = true;
}
/**
 * 检验是否会产生合班课
 */

function hasMergedClassCourse(lessonTime) {
    var lessonTimeCol = $("#lessonTime_area_" + lessonTime);
    //var items = lessonTimeCol.find("div");
    //var teacherId = curSelectedTeachingPlan.teacherId;
    //for(var i=0;i<items.length;i++){
    //    alert($(items[i]).attr("teacherId"));
    //    if(teacherId ==$(items[i]).attr("teacherid") ){
    //        return true;
    //    }
    //}
    if (curSelectedTeachingPlan != null) {
        if(curSelectedTeachingPlan.teacherId > 0){
            var flag = lessonTimeCol.find("div[teacherId = '" + curSelectedTeachingPlan.teacherId + "']");
            if (flag.length > 0) {
                return true;
            }
        }else{  // 考虑多个老师的问题
            var flag = lessonTimeCol.find("div[groupId = '" + curSelectedTeachingPlan.groupId + "']");
            if (flag.length > 0) {
                return true;
            }
        }
    }
    return false;
}
function checkPutCourses(teachingPlans, lessonTime) {
    for (var i = 0; i < teachingPlans.length; i++) {
        if (!checkPutCourse(teachingPlans[i], lessonTime)) {
            return false;
        }
    }

    return true;
}

// 校验当前课时是否可安排
function checkPutCourse(teachingPlan, lessonTime) {

    // 当前没选择，不安排
    if (teachingPlan == null) {
        return false;
    }

    var lessonTimeCol = $("#lessonTime_area_" + lessonTime);

    // 校验班级时间冲突
    var classLessonTimeConflict = false;
    lessonTimeCol.find("div[classId='" + teachingPlan.classId + "']").each(function () {
        classLessonTimeConflict = true;
    });
    if (classLessonTimeConflict) {
        showMessage("此班级在此时间已安排了课程！");
        return false;
    }

    // 同一教师同一时间，不同课判断
    //TODO: shit , the conflict between teachers is very defficult .
    var teacherLessonTimeConflict = false;
    if(teachingPlan.teacherId > 0){
        lessonTimeCol.find("div[teacherId='" + teachingPlan.teacherId + "']").each(function () {
            var teachingPlanId = $(this).attr("teachingPlanId");
            var tp = teachingPlanPool.get(teachingPlanId);

            // 课程不同的有冲突，相同的可以合班
            if (tp.courseId != teachingPlan.courseId) {
                teacherLessonTimeConflict = true;
            }
        });
    }else{
        lessonTimeCol.find("div[groupId='" + teachingPlan.groupId + "']").each(function () {
            var teachingPlanId = $(this).attr("teachingPlanId");
            var tp = teachingPlanPool.get(teachingPlanId);

            // 课程不同的有冲突，相同的可以合班
            if (tp.courseId != teachingPlan.courseId) {
                teacherLessonTimeConflict = true;
            }
        });
    }
    //TODO：下面处理 多个老师互相冲突的问题 上面已经处理了Id完全相同的情况
    if(!teacherLessonTimeConflict){
        var items = lessonTimeCol.find("div");
        if(items.length > 0){
            for(var i=0; i< items.length;i++){
                var teachingPlanId = $(items[i]).attr("teachingPlanId");
                var tp = teachingPlanPool.get(teachingPlanId);
                // 老师互相冲突
                teacherLessonTimeConflict = isTeacherTimeConflict(teachingPlan.teacherId,teachingPlan.teacherIds,tp.teacherId,tp.teacherIds);
                // TODO： 如果一个老师冲突就算全部冲突
                //if(teacherLessonTimeConflict){
                //    // 课程不同的有冲突，相同的可以合班
                //    if(tp.courseId == teachingPlan.courseId){
                //        if(confirm("这两门课有相同的代课老师，此行为会产生合班操作，是否继续？")){
                //            teacherLessonTimeConflict = false;
                //        }
                //    }
                //}
                if(teacherLessonTimeConflict){  //如果冲突 ，直接跳出
                    break;
                }

            }
        }
    }
    if (teacherLessonTimeConflict) {
        showMessage("此教师在此时间已安排了课程！");
        //alertWarning("此教师在此时间已安排了课程！");
        return false;
    }

    //// 教师课程安排判断
    //var coursePlanValue = createCoursePlanValue(teachingPlan, lessonTime)
    //for (var i = 0; i < coursePlanValueList.length; i++) {
    //    if (coursePlanValue == coursePlanValueList[i]) {
    //        showMessage("此教师在此时间已安排了相同课程！");
    //        //alertWarning("此教师在此时间已安排了相同课程！");
    //        return false;
    //    }
    //}

    // 周课时数判断
    if (teachingPlan.lessonsPerWeek <= teachingPlan.lessonsUsed) {
        showMessage("此教师周课时已经排满！");
        //alertWarning("此教师周课时已经排满！");
        return false;
    }

    return true;
}
/**
 * 多个老师互相包含
 * @param teacherId1
 * @param teacherId2
 * @param teacherIds1
 * @param teacherIds2
 */
function isTeacherTimeConflict(teacherId1,teacherIds1,teacherId2,teacherIds2){
    if(teacherId1 > 0 && teacherIds2 != null){
        for(var i = 0 ; i <teacherIds2.length; i++){
            if(teacherId1 == teacherIds2[i]){
                return true;
            }
        }
    }
    if(teacherId2 > 0 && teacherIds1 != null){
        for(var i = 0;i <teacherIds1.length; i++){
            if(teacherId2 == teacherIds1[i]){
                return true;
            }
        }
    }
    if(teacherIds1 != null && teacherIds2 != null){
        for(var i = 0; i < teacherIds1.length; i++){
            for(var j = 0;j < teacherIds2.length; j++){
                if(teacherIds1[i] == teacherIds2[j]){
                    return true;
                }
            }
        }
    }
    return false;
}
// 添加到控件里
function appentToLessonTimeCol(teachingPlan, lessonTime) {
    var lessonTimeCol = $("#lessonTime_area_" + lessonTime);
    var appendHtml = "<div style='text-align:center;' area='course' teachingPlanId='" + teachingPlan.id + "' " +
        "gradeId='course_" + teachingPlan.gradeId + "' classId='" + teachingPlan.classId + "' " +
        "teacherId='" + teachingPlan.teacherId + "' " +"groupId='" + teachingPlan.groupId +"'>";

    if(isMyTask) {
        appendHtml += "<span class='remove-course' title='删除' onclick=\"removeCourse(event,'" + teachingPlan.id + "','" + lessonTime + "')\">&times;</span> "
    }

    appendHtml += teachingPlan.courseName + "-" + teachingPlan.gradeName + teachingPlan.className + "</div>";

    var html = lessonTimeCol.html();
    html += appendHtml;
    lessonTimeCol.html(html);
}


// 移除已安排的课程
function removeCourse(e, teachingPlanId, lessonTime) {

    var teachingPlan = getFromTeachingPlanPool(teachingPlanId);
    var mergedClassTeachingPlans = getMergedClassTeachingPlans(teachingPlan);

    var lessonTimeCol = $("#lessonTime_area_" + lessonTime);

    for (var i = 0; i < mergedClassTeachingPlans.length; i++) {
        var tp = mergedClassTeachingPlans[i];
        // 已选课时数-1
        tp.lessonsUsed--;
        // 从当前已排的课程中删除
        removeFromCoursePlanValueList(tp, lessonTime);
        lessonTimeCol.find("div[teachingPlanId='" + tp.id + "']").remove();
        // 设置控件上的课时显示
        setTeachingPlanColLessons(tp);
    }
    //
    hasChanged = true;
    //阻止冒泡
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    else if (window.event) {
        e.cancelBubble = true;
    }

}

// 设置teachingPlan列表中的课时显示
function setTeachingPlanColLessons(teachingPlan) {
    var teachingPlanCol = getTeachingPlanCol(teachingPlan); //$("#tp" + teachingPlan.id);
    var tpLessonsCol = teachingPlanCol.find("td[field='lessons']");
    tpLessonsCol.html(teachingPlan.lessonsUsed + "/" + teachingPlan.lessonsPerWeek);
}

// 添加到courseplanvaluelist
function addToCoursePlanValueList(teachingPlan, lessonTime) {

    // 插入一个空的，表示此teachingPlan有过设置，只插入一次，空的值将不会删除，方便更新时操作
    var coursePlanValue = createCoursePlanValue(teachingPlan, '-1');
    doAddToCoursePlanValueList(coursePlanValue);

    // 插入非空值
    coursePlanValue = createCoursePlanValue(teachingPlan, lessonTime)
    return doAddToCoursePlanValueList(coursePlanValue);
}

function doAddToCoursePlanValueList(coursePlanValue) {
    for (var i = 0; i < coursePlanValueList.length; i++) {
        if (coursePlanValue == coursePlanValueList[i]) {
            return false;
        }
    }

    coursePlanValueList.push(coursePlanValue);

    return true;
}

// 从coursePlanValueList里移除
function removeFromCoursePlanValueList(teachingPlan, lessonTime) {
    var coursePlanValue = createCoursePlanValue(teachingPlan, lessonTime)

    var removeIndex = 0;
    for (var i = 0; i < coursePlanValueList.length; i++) {
        removeIndex = i;
        if (coursePlanValue == coursePlanValueList[i]) {
            break;
        }
    }

    coursePlanValueList.splice(removeIndex, 1);
}

// 构建createCoursePlanValue
function createCoursePlanValue(teachingPlan, lessonTime) {
    var coursePlanValue = teachingPlan.id + "|" + lessonTime;
    return coursePlanValue;
}

function createTeachingPlanId(teachingPlan) {
    if (teachingPlan) {
        var teachingPlanId = "_"
        + teachingPlan.classId + "_"
        + teachingPlan.courseId + "_"
        + teachingPlan.teacherId + "_"
        + teachingPlan.groupId;
        return teachingPlanId;
    }

    return "";
}

//=================显示年级课程

// 显示年级课程
function showCourseOfGrade(gradeId) {
    var chkGrade = $("#chkGrade_" + gradeId);
    var checked = chkGrade.is(':checked');
    $("div[gradeId='course_" + gradeId + "']").each(function () {
        if (checked) {
            $(this).show();
        }
        else {
            $(this).hide();
        }
    });
}

//========================保存相关=====

// 自动保存
function autoSave() {
    // 自动保存调用时间间隔
    var t = 1 * 1000;

    if (hasChanged) {
        save(false, function () {
            setTimeout(function () {
                autoSave();
            }, t);
        });

        hasChanged = false;
    }
    else {
        setTimeout(function () {
            autoSave();
        }, t);
    }
}

// 保存
function save(isShowMsg, completeCallback) {
    if (coursePlanValueList == null) {
        return;
    }
    if (coursePlanValueList.length == 0) {
        if (isShowMsg) {
            alertInfo("没有需要保存的内容！")
        }
        return;
    }
    if (isShowMsg) {
        alertInfo("保存中...")
    }

    jQuery.ajax({
        type: "POST",
        url: baseUrl + "/courseplan/preschedule/save?taskId=" + taskId,
        data: "datas=" + decodeURIComponent(coursePlanValueList.join(",")),
        success: function (ret) {
            if (ret != "0") {
                if (isShowMsg) {
                    alertInfo("保存成功");
                }
            } else {
                if (isShowMsg) {
                    alertInfo("保存失败");
                }
            }
        },
        error: function () {
            if (isShowMsg) {
                alertInfo("出错了，保存失败");
            }
        },
        complete: function () {
            if (completeCallback) {
                completeCallback();
            }
        }

    });
}
/**
 * 清空所有预排
 */
function clearPreschedule(){
    if (confirm("确认要清空所有预排课程么？")){
        jQuery.ajax({
            type:"GET",
            url: baseUrl + "/courseplan/preschedules?taskId=" + taskId,
            success: function(ret){
                if (ret != null && ret.code == "1"){
                    reloadPage();
                }else if(ret != null){
                    alertInfo(ret.msg);
                }
            }
        });
    }
}
function reloadPage() {
    window.location.href="/m/courseplan/preschedule?taskId=" + taskId;
}
/*region 页面提示相关*/
function alertSuccess(msg) {
    var html = new Array();
    html.push("<div class='alert alert-success'>");
    html.push(msg);
    html.push("</div>");
    $("#alertDiv").html(html.join(""));
    $("#alertDiv").show();
    $("#alertDiv").find("div").fadeOut(3000);
}
function alertWarning(msg) {
    var html = new Array();
    html.push("<div class='alert alert-warning'>");
    html.push(msg);
    html.push("</div>");
    $("#alertDiv").html(html.join(""));
    $("#alertDiv").show();
    $("#alertDiv").find("div").fadeOut(3000);
}
function alertInfo(msg, fadeOutTime) {
    var html = new Array();
    html.push("<div class='alert alert-info'>");
    html.push(msg);
    html.push("</div>");
    $("#alertDiv").html(html.join(""));
    $("#alertDiv").show();

    var time = 2000;
    if (fadeOutTime) {
        time = fadeOutTime;
    }

    $("#alertDiv").fadeOut(time);
}

function hideAlertInfo() {
    $("#alertDiv").stop(true);
    $("#alertDiv").hide()
}
/*endregion 页面提示相关*/

// 校验不可用的课时
function checkDisabledLessonTimes() {
    var checked = isOpenCheckDisabledLessonTimes();
    var isDisabled = checked ? "true" : "false";
    setLessonTimesDisabled(isDisabled);
}

// 是否开启校验
function isOpenCheckDisabledLessonTimes() {
    return $("#chkOpenLessonTimesVerify").is(':checked');
}

// 设置不能排课时间
function setLessonTimesDisabled(isDisabled) {
    if (curSelectedTeachingPlan == null) {
        return;
    }
    // 不排课时间
    var disabledLessonTimeBox = {
        lessonTimes: []
    };

    var doneCount = 0;
    // 遍历所有当前合班的班级
    for (var i = 0; i < curSelectedMergedClassTeachingPlans.length; i++) {
        var tp = curSelectedMergedClassTeachingPlans[i];

        if (!stringIsNullOrEmpty(tp.disabledLessonTimes)) {
            disabledLessonTimeBox.lessonTimes = disabledLessonTimeBox.lessonTimes.concat(eval(tp.disabledLessonTimes));

            doneCount++;
            if (doneCount == curSelectedMergedClassTeachingPlans.length) {
                setDisabledLessonTimeCols(disabledLessonTimeBox.lessonTimes, isDisabled);
                return;
            }
            else {
                continue;
            }
        }

        var gradeId = tp.gradeId;
        var classId = tp.classId;
        var courseId = tp.courseId;
        var teacherIds = tp.teacherIds.join(",");

        jQuery.ajax({
            cache: false,
            //url: baseUrl + "/courseplan/preschedule/disabledLessonTime",
            url: baseUrl + "/courseplan/preschedule/disabledLessonTimeOfMultiTeacher",
            data: "taskId=" + taskId + "&gradeId=" + gradeId + "&classId=" + classId + "&courseId=" + courseId + "&teacherIds=" + teacherIds,
            success: getDisabledLessonTimeCallbackFunc(tp, disabledLessonTimeBox),
            complete: function () {
                doneCount++;
                if (doneCount == curSelectedMergedClassTeachingPlans.length) {
                    setDisabledLessonTimeCols(disabledLessonTimeBox.lessonTimes, isDisabled);
                }
            }
        });
    }
}

/**
 *
 */
function getDisabledLessonTimeCallbackFunc(teachingPlan, disabledLessonTimeBox) {
    var func = function (ret) {
        if (ret != "") {
            var dlts = eval(ret);
            disabledLessonTimeBox.lessonTimes = disabledLessonTimeBox.lessonTimes.concat(dlts);
            teachingPlan.disabledLessonTimes = ret;
        }
    }

    return func;
}

function setDisabledLessonTimeCols(disabledLessonTimes, isDisabled) {
    // 是否开启校验
    var isOpenCheck = isOpenCheckDisabledLessonTimes();
    //var bgColor = isDisabled == "true" && isOpenCheck ? "#f5f5f5" : "#fff";
    var isLessonTimeDisabled = isDisabled == "true" && isOpenCheck;
    isDisabled = isLessonTimeDisabled ? "true" : "false";

    for (var i = 0; i < disabledLessonTimes.length; i++) {
        var lessonTime = disabledLessonTimes[i];

        var lessonArea = $("#lessonTime_area_" + lessonTime);
        lessonArea.removeClass("lesson-time-disabled");
        if (isLessonTimeDisabled) {
            lessonArea.addClass("lesson-time-disabled")
        }
        lessonArea.attr("isDisabled", isDisabled);
    }
}

function clearDisabledLessonTimes() {
    $("td[areaName='lessonTimeArea']").each(function () {
        var col = $(this);
        col.removeClass("lesson-time-disabled");
        col.attr("isDisabled", "false");
    });
}


//====

/**
 * 从此步开始
 *
 */
function startFromHere() {
    if (confirm("将会把已排好的课删除，并不可恢复！确认进行此操作？")) {
        // 删除排好的课程
        $.ajax({
            type: "POST",
            url: baseUrl + "/courseplan/delete?taskId=" + taskId,
            success: function (ret) {
                if (ret == "1") {
                    //showMessage("操作完成！");
                    alertInfo("操作完成！");
                }
            }
        });
    }
}

// 显示提示信息
function showMessage(msg, title) {
    $("#alert_container").remove();

    var html = "<div id=\"alert_container\" class=\"h5\" style='padding-left:10px;'><p id=\"alert_msg\"></p></div>";
    $("body").append(html);
    $("#alert_msg").html(msg);

    if (stringIsNullOrEmpty(title)) {
        title = "提示";
    }

    $("#alert_container").dialog({
        closeText: "关闭",
        title: title,
        width: 350,
        height: 120
    });
}


function preview(){
    var url = baseUrl + "/courseplan/preschedule/class?taskId=" + taskId
    window.open(url);
}

Array.prototype.indexOf = function (obj) {
    for (i = 0; i < this.length; i++) {
        if (obj == this[i]) {
            return i;
        }
    }
    return -1;
}

